import { Button, Form, Space } from '@douyinfe/semi-ui';
import {
  debounce,
  identity,
  isEqual,
  isNil,
  isNumber,
  omitBy,
  pickBy,
} from 'lodash';
import { useCallback, useMemo } from 'react';
import { IQueryParams } from '@/widgets/table-pagination';
import { usePageContext } from './context';
import { OrganizeStatus, initialFilter } from './helper';

const OrganizeFilter = () => {
  const { Option } = Form.Select;
  const PageContext = usePageContext();
  const PageAction = useMemo(() => {
    return {
      addRecord: PageContext.addRecord,
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
    };
  }, [PageContext]);

  const applyFilter = useCallback(
    (values: any) => {
      const _queryParams: IQueryParams = {
        ...PageAction.queryParams,
        filter: { ...pickBy(values, identity), ...pickBy(values, isNumber) },
      };
      if (!isEqual(_queryParams, PageAction.queryParams)) {
        PageAction.setQueryParams({ ..._queryParams, pageNum: 1 });
      }
    },
    [PageAction.queryParams]
  );

  return (
    <Form
      labelPosition='left'
      className='gap-x-2 items-start'
      validateFields={() => ''}
      layout='horizontal'
      // onChange={(e) => {}}
      // onSubmit={() => {}}
      initValues={initialFilter}
      onValueChange={debounce((values, changedValue) => {
        applyFilter(values);
      }, 350)}
      onReset={() => applyFilter(initialFilter)}>
      <Form.Input
        field='name'
        label='组织名称'
        trigger='blur'
        placeholder='请输入组织名称'
      />
      <Form.Select
        field='status'
        label='状态'
        placeholder='请选择'
        showClear
        className='w-[100px]'>
        {Object.values(OrganizeStatus).map((status) => (
          <Option key={status.value} value={status.value}>
            {status.text}
          </Option>
        ))}
      </Form.Select>
      <Button htmlType='reset'>重置</Button>
    </Form>
  );
};

export default OrganizeFilter;
